import { GetSelectQuestionListApi } from "@/api";
import { Button } from "@mui/material";
import React, { useEffect, useState } from "react";
import { useNavigate, useParams } from "react-router-dom";
import SelectList from "./components/SelectList";
import "./select.less";

const type1: IOption[] = [
  { text: "全部", value: "all" },
  { text: "错误", value: "err" },
  { text: "已做", value: "done" },
  { text: "未做", value: "notdone" },
];

const typenum: IOption[] = [
  { text: "5", value: "5" },
  { text: "10", value: "10" },
  { text: "20", value: "20" },
  { text: "30", value: "30" },
  { text: "50", value: "50" },
  { text: "100", value: "100" },
];

// 下面这个代码，先抄
interface MapQsType {
  [index: string]: string;
}
const mapQsType: MapQsType = {
  all: "全部",
  qa: "问答",
  one: "单选",
  check: "判断",
  code: "编程",
  many: "多选",
  fill: "填空",
};

// 用于选择题目，点击练习跳转到 Practice的页面
export default function Select() {
  // 这个函数是传递到子组件里面获取选中的对应 typeType
  const selectTestType = (value: string) => {
    // console.log(value);
    setTestType(value);
  };

  // 这个函数从子组件里面得到选中了多少题目
  const selectTestNum = (value: string) => {
    // console.log(parseInt(value));
    setTestNum(parseInt(value));
  };

  // 得到url上面的actionCode
  const { actionCode } = useParams<{ actionCode: string }>();
  // 中间题目类型的数组
  const [qsType, setQSType] = useState<IOption[]>([]);
  const selectQsType = (value: string) => {
    setQuestionType(value);
  };
  useEffect(() => {
    GetSelectQuestionListApi(actionCode!).then((res) => {
      if (res.errCode === 0) {
        // 得到中间选项列表的数据
        // 但是现在得到的是  {key:tring;value:number;sort:number} 的数据
        // 最终我们要的是 {text:string;value:string} 的数据
        // 转换
        const list = res.data.map((item) => {
          // return { text: "题目类型中文+数量", value: "题目类型英文" };
          return {
            text: `${mapQsType[item.key]}${item.value}`,
            value: item.key,
          };
        });
        setQSType(list);
      }
    });
  }, []);

  // 选择了多题
  const [testNum, setTestNum] = useState(5);
  const [testType, setTestType] = useState("all");
  const [questionType, setQuestionType] = useState("all");

  const navigate = useNavigate();
  const toPractice = () => {
    navigate("/practice", {
      state: {
        actionCode,
        testNum,
        testType,
        questionType,
      },
    });
  };

  return (
    <div className="select">
      <section className="goto-practice flex between">
        <Button variant="contained" onClick={toPractice}>
          进入练习模式
        </Button>
        <Button variant="contained" color="warning">
          进入考试模式
        </Button>
      </section>
      <SelectList title="试题分类" list={type1} onChange={selectTestType} />
      <SelectList list={qsType} title="题目分类" onChange={selectQsType} />
      <SelectList title="做题数量" list={typenum} onChange={selectTestNum} />
    </div>
  );
}
